package admin

import (
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/utils/captcha"
	"object/go_cms/models"
)

type LoginAdminController struct {
	BaseAdminController
	models models.AdminModels
}

var cpt *captcha.Captcha

//验证码
func init() {
	store := cache.NewMemoryCache()
	cpt = captcha.NewWithFilter("/captcha/", store)
	cpt.ChallengeNums = 4
	cpt.StdWidth = 100
	cpt.StdHeight = 40
}

// 登录页面
// @router /admin/login [get]
func (c *LoginAdminController) LoginUI() {
	c.TplAdmin("login")
}

//登录提交
// @router /admin/login_sub [get,post]
func (c *LoginAdminController) Login() {
	if !cpt.VerifyReq(c.Ctx.Request) {
		//验证码错误
		c.Res.Code = 0
		c.Res.Msg = "验证码错误"
	} else {
		//验证码正确
		user_name := c.GetString("user_name")
		pass := c.GetString("password")
		//验证登录信息
		admin, _ := c.models.LoginAdmin(user_name, pass)
		if admin.Id != 0 {
			c.SetSession("aid", admin.Id)
			c.Res.Code = 1
			c.Res.Msg = "登录成功"
		} else {
			c.Res.Code = 0
			c.Res.Msg = "用户名或密码错误"
		}
	}
	c.Json(c.Res)
}

// 退出登录
// @router /admin/login_out [get,post]
func (c *LoginAdminController) LoginOut() {
	if c.GetSession("aid") != nil {
		c.DelSession("aid")
	}
	if c.IsAjax() {
		c.Res.Code = 1
		c.Res.Msg = "退出成功"
		c.Json(c.Res)
	} else {
		c.Redirect("/admin/login", 302)
	}
}
